package com.hrt.log;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import com.btcode.common.MyLog;
import com.btcode.log.ILog;
import com.hrt.datasender.mq.MqKit;

public final class LogMonitor {

    private static volatile LogMonitor instance;

    private ILog log;

    private LogMonitorCompare logMonitorCompare = new LogMonitorCompare();

    private LogMonitor() {
        log = MyLog.getInstance().getLogger(getClass());
    }

    public static LogMonitor getInstance() {
        if (instance == null) {
            synchronized (LogMonitor.class) {
                if (instance == null) {
                    instance = new LogMonitor();
                }
            }
        }
        return instance;
    }

    private HashMap<String, Log4MQ> logMap = new HashMap<>();

    public void push(String name, Log4MQ log) {
        logMap.put(name, log);
        this.log.info("注册监控：" + name);
    }

    public List<MonitorModel> getMonitorModelList() {

        List<MonitorModel> models = new ArrayList<>();

        for (Entry<String, Log4MQ> entry : logMap.entrySet()) {
            Log4MQ log = entry.getValue();
            MonitorModel model = buildMonitorModel(log);

            models.add(model);
        }

        Collections.sort(models, logMonitorCompare);

        return models;
    }

    /**
     * 通过前缀获取一批监控对象
     * 
     * @param prefix
     * @return
     */
    public List<MonitorModel> getMonitorModelListByPrefix(String prefix) {

        List<MonitorModel> models = new ArrayList<>();

        for (Entry<String, Log4MQ> entry : logMap.entrySet()) {

            String name = entry.getKey();

            if (name.startsWith(prefix)) {
                Log4MQ log = entry.getValue();

                MonitorModel model = buildMonitorModel(log);

                models.add(model);
            }
        }

        return models;

    }

    public Log4MQ getMonitorModel(String id) {
        Log4MQ log = logMap.get(id);

        return log;
    }

    public MonitorModel buildMonitorModel(Log4MQ log) {

        if (log == null) {
            return null;
        }

        int msgSize = MqKit.getMqMsgSize(log.getName());
        int errrorMsgSize = MqKit.getMqMsgSize(log.getName() + ".error");

        MonitorModel model = new MonitorModel();
        model.setErrorCount(errrorMsgSize);
        model.setLogCount(msgSize);
        model.setMonitorId(log.getName());
        model.setMonitorName(log.getName());

        return model;
    }
}
